/**
 * 作者:李杰
 * email: maillijie@gmail.com
 */
package com.javainfo.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javainfo.util.Const;

public class Struts2Filter extends StrutsPrepareAndExecuteFilter{

    private static final Logger logger = LoggerFactory
			.getLogger(Struts2Filter.class);
	
    public static final String HTTP_METHOD_PARAM = "_method";
    
	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		String requestPath = ((HttpServletRequest) req).getRequestURI()
				.replaceFirst(((HttpServletRequest) req).getContextPath(), "");
		String reqMethod = ((HttpServletRequest) req).getMethod();

		if ((requestPath.indexOf("/fckeditor") >= 0
				|| requestPath.indexOf("css/") >= 0
				|| requestPath.indexOf("js/") >= 0
				|| requestPath.indexOf("errors/") >= 0 || requestPath
				.indexOf("images/") >= 0)
				&& (requestPath.indexOf("struts/") < 0)) {
			logger.info("用户发出请求:" + reqMethod + requestPath);
			chain.doFilter(req, res);
		} else if (!isGet((HttpServletRequest) req)) {
			logger.info("用户发出请求:" + reqMethod + requestPath);
			super.doFilter(req, res, chain);
		} else {
			logger.info("用户发出请求并且被记录:"+ reqMethod + requestPath);
			List<String> viewHistory = (List<String>) ((HttpServletRequest) req)
					.getSession().getAttribute(Const.VIEW_HISTORY);
			if(viewHistory==null){
				viewHistory = new ArrayList<String>();
				viewHistory.add(requestPath);
				((HttpServletRequest) req).getSession().setAttribute(Const.VIEW_HISTORY, viewHistory);
			}else{
				viewHistory.add(requestPath);
			}
			super.doFilter(req, res, chain);
		}
	}
	
    protected boolean isGet(HttpServletRequest request) {
        return "get".equalsIgnoreCase(request.getMethod());
    }

    protected boolean isPost(HttpServletRequest request) {
        return "post".equalsIgnoreCase(request.getMethod());
    }

    protected boolean isPut(HttpServletRequest request) {
        if ("put".equalsIgnoreCase(request.getMethod())) {
            return true;
        } else {
            return isPost(request) && "put".equalsIgnoreCase(request.getParameter(HTTP_METHOD_PARAM));
        }
    }

    protected boolean isDelete(HttpServletRequest request) {
        if ("delete".equalsIgnoreCase(request.getMethod())) {
            return true;
        } else {
            return "delete".equalsIgnoreCase(request.getParameter(HTTP_METHOD_PARAM));
        }
    }
}
